package tech.luoyu.ki.service;

import java.util.List;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import tech.luoyu.ki.entity.auto.SysUser;
import tech.luoyu.ki.entity.auto.SysUserExample;
import tech.luoyu.ki.entity.auto.SysUserExample.Criteria;
import tech.luoyu.ki.mapper.auto.SysUserMapper;
import tech.luoyu.ki.util.CacheUtil;
import tech.luoyu.ki.vo.Constants;
import tech.luoyu.ki.vo.ReturnResult;

@Service
@Transactional
public class UserService {
	@Resource
	private SysUserMapper userMapper;

	public ReturnResult add(SysUser user) {
		ReturnResult rs = new ReturnResult();

		SysUser exist = getByLoginName(user.getLoginName());
		if (exist != null) {
			rs.setCode(0);
			rs.setMessage("登录账号已存在");
			return rs;
		}

		user.preInsert();
		user.setLoginPassword("admin");
		userMapper.insert(user);

		rs = new ReturnResult(1, "添加成功");
		rs.putData("entity", user);
		return rs;
	}

	public ReturnResult update(SysUser user) {
		ReturnResult rs = new ReturnResult();

		SysUser exist = getByLoginName(user.getLoginName());
		if (exist != null && !exist.getId().equals(user.getId())) {
			rs.setCode(0);
			rs.setMessage("登录账号已存在");
			return rs;
		}

		user.preUpdate();
		int effectRow = userMapper.updateByPrimaryKeySelective(user);

		rs = new ReturnResult(1, "更新成功");
		rs.putData("effectRow", effectRow);
		return rs;
	}

	public ReturnResult delete(String id) {
		int effectRow = userMapper.deleteByPrimaryKey(id);
		ReturnResult rs = new ReturnResult(1, "删除成功");
		rs.putData("effectRow", effectRow);
		return rs;
	}

	public ReturnResult get(String id) {
		SysUser entity = userMapper.selectByPrimaryKey(id);
		ReturnResult rs = new ReturnResult(1, "查询成功");
		rs.putData("entity", entity);
		return rs;
	}

	public ReturnResult list() {
		List<SysUser> list = (List<SysUser>) CacheUtil.get("user", "list");

		if (list == null) {
			SysUserExample example = new SysUserExample();
			Criteria c = example.createCriteria();
			c.andDataStatusEqualTo(Constants.STATUS_NORMAL);
			example.setOrderByClause(" updateTime desc");

			list = userMapper.selectByExample(example);
			CacheUtil.put("user", "list", list);
		}

		ReturnResult rs = new ReturnResult(1, "查询成功");
		rs.putData("list", list);
		return rs;
	}

	public SysUser getByLoginName(String loginName) {
		SysUserExample example = new SysUserExample();
		Criteria c = example.createCriteria();
		c.andDataStatusEqualTo(Constants.STATUS_NORMAL);
		c.andLoginNameEqualTo(loginName);
		List<SysUser> list = userMapper.selectByExample(example);
		if (list.size() > 0) {
			return list.get(0);
		} else {
			return null;
		}
	}
}
